#include "MapCacherWorkQueue.h"
#include "OCMain/FileUtil.h"

namespace OCPP
{
	std::map<String, int> MapCacherWorkQueue::_badLayerMap;

	MapCacherWorkQueue::MapCacherWorkQueue(bool startup)
		:mDefaultWorkQueue("Defautl")
	{
		mDefaultWorkQueue.setWorkerThreadCount(1);
		mWorkQueueChannel = mDefaultWorkQueue.getChannel("Default");
		mDefaultWorkQueue.addResponseHandler(mWorkQueueChannel, this);
		mDefaultWorkQueue.addRequestHandler(mWorkQueueChannel, this);
		if (startup)
		{
			mDefaultWorkQueue.startup();
		}
	}

	MapCacherWorkQueue::~MapCacherWorkQueue()
	{
		
	}

	void MapCacherWorkQueue::startup()
	{
		mDefaultWorkQueue.startup();
	}

	void MapCacherWorkQueue::processResponses()
	{
		mDefaultWorkQueue.processResponses();
	}

	void MapCacherWorkQueue::addRequest(TaskRequest request, int priority)
	{
		mDefaultWorkQueue.addRequest(mWorkQueueChannel, request.type, Any(request), priority);
	}

	Response* MapCacherWorkQueue::handleRequest(const Request* req, const WorkQueue* srcQ)
	{
		if (req->getAborted())
		{
			return new Response(req, false, req->getData());
		}

		TaskRequest anyRequest = any_cast<TaskRequest>(req->getData());

		String url = anyRequest.url;
		String path = anyRequest.path;
		String fileName = anyRequest.fileName;
		String layer = anyRequest.layer;
		
		long lHTTPSCode;
		HttpClientEx httpClient([](const String& message)
			{
				OCPP_LOG_ERROR << message << "\n";
			});
		httpClient.SetTimeout(10);

		if (!FileUtil::existFile(path))
		{
			FileUtil::makeDirectory(path);
		}

		bool result = httpClient.fetchFile(url, fileName);
		if (!result)
		{
			_badLayerMap[layer]++;
		}
		else
		{
			OCPP_LOG_INFO << fileName << " new Cache.\n";
			_badLayerMap[layer] = 0;
		}

		return new Response(req, true, Any(anyRequest));
	}

	void MapCacherWorkQueue::handleResponse(const Response* res, const WorkQueue* srcQ)
	{
		TaskRequest anyRequest = any_cast<TaskRequest>(res->getData());
		if (res->getRequest()->getAborted() || !res->succeeded())
		{
			return;
		}
	}
}
